Page({
  data: {
    images: [],
    bikeName: '点击选择',
    name: '点击选择',
    address: '点击选择',
    sendTime: '立即发送',
    longitude: 0,
    latitude: 0,
    inputValue: ''
  },

  onLoad: function (event) {
    this.getAllBikes()
  },

  chooseImage: function () {
    const that = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success(res) {
        const newImage = res.tempFiles[0].tempFilePath;
        that.setData({
          images: that.data.images.concat(newImage)
        })
      }
    })
  },

  removeImage() {
    this.setData({
      images: this.data.images.slice(0, -1)
    })
  },

  showActionSheet1() {
    const that = this
    const items = wx.getStorageSync('bikeNames')
    wx.showActionSheet({
      itemList: items,
      success(res) {
        that.setData({
          bikeName: items[res.tapIndex]
        })
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },

  showActionSheet2() {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        var name = res.name
        var address = res.address
        var latitude = res.latitude
        var longitude = res.longitude
        that.setData({
          name: name,
          address: address,
          latitude: latitude,
          longitude: longitude
        })
      },
      complete(r) {
        console.log(r)
      }
    })
  },

  showActionSheet3() {
    const that = this
    const items = ['立即发送', '5分钟后', '10分钟后']
    wx.showActionSheet({
      itemList: items,
      success(res) {
        that.setData({
          sendTime: items[res.tapIndex]
        })
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },

  // 获取所有单车类型名称
  getAllBikes() {
    wx.request({
      url: getApp().globalData.commonIP + '/bike/allBikeNames',
      method: 'GET',
      header: {
        'content-type': 'application/json', // 默认值
        'token': wx.getStorageSync('token')
      },
      success: res => {
        if (res.data.msg == "token过期，请重新登录" || res.data.msg == "token失效，请重新登录" || res.data.msg == "无效签名，请重新登录" || res.data.msg == "token算法不一致，请重新登录") {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
            complete: (res) => {
              if (res.cancel) {

              }

              if (res.confirm) {
                // 重置全局变量和去除缓存
                getApp().globalData.wxusername = ''
                getApp().globalData.wxuseravatar = ''
                wx.removeStorageSync('nickName')
                wx.removeStorageSync('avatarUrl')
                wx.removeStorageSync('token')

                wx.switchTab({
                  url: '/pages/index/index'
                })
              }
            }
          })
          return
        }
        wx.setStorageSync('bikeNames', res.data.data)
      }
    })
  },

  returnIndex: function () {
    wx.navigateBack();
  },

  handleInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  },

  // 发送乱停乱放请求
  sendMsg() {
    var ifok = false
    var errmsg = ''
    // 判断图片是否符合要求
    if (this.data.images[0] == null) {
      ifok = true
      errmsg = '请上传一张此路段图片！'
    }
    // 判断文字是否超限
    const app = getApp()
    var words = app.countChineseCharacters(this.data.inputValue)
    if (words > 100) {
      ifok = true
      errmsg = '发送文字数不得超过100字！'
    }
    // 判断单车名称、地址和字段是否都不为空
    if (this.data.bikeName == '点击选择' || this.data.bikeName == null || this.data.bikeName == '') {
      ifok = true
      errmsg = '单车名称不得为空！'
    }
    if (this.data.name == '点击选择' || this.data.name == null || this.data.name == '') {
      ifok = true
      errmsg = '地址不得为空！'
    }
    if (this.data.address == '点击选择' || this.data.address == null || this.data.address == '') {
      ifok = true
      errmsg = '路段不得为空！'
    }
    // 综合判断
    if (ifok) {
      wx.showModal({
        title: '发送失败',
        content: errmsg,
        showCancel: false
      })
      return
    }
    var that = this
    wx.showModal({
      title: '提示',
      content: '确定要发送吗？',
      complete: (res) => {
        if (res.cancel) {

        }

        if (res.confirm) {
          wx.showLoading({
            title: '正在加载...'
          });
          // 发起网络请求，下载图片内容，将其转换成base64
          let imgList = [];
          const promises = []; // 用于存储下载图片的 Promise

          that.data.images.forEach(imageUrl => {
            const promise = new Promise((resolve, reject) => {
              const imgBehind = imageUrl.split('.')
              wx.downloadFile({
                url: imageUrl,
                success: (res) => {
                  if (res.statusCode === 200) {
                    wx.getFileSystemManager().readFile({
                      filePath: res.tempFilePath,
                      encoding: 'base64',
                      success: (res) => {
                        imgList.push("data:image/" + imgBehind[imgBehind.length - 1] + ";base64," + res.data);
                        resolve(); // 标记当前 Promise 已完成
                      },
                      fail: (error) => {
                        console.error('Error:', error);
                        reject(error); // 标记当前 Promise 失败
                      }
                    });
                  } else {
                    reject(new Error('Download failed'));
                  }
                },
                fail: (error) => {
                  console.error('Error:', error);
                  reject(error); // 标记当前 Promise 失败
                }
              });
            });
            promises.push(promise); // 存储 Promise
          });

          // 等待所有 Promise 完成后打印 imgList
          Promise.all(promises)
            .then(() => {
              // 发送请求
              wx.request({
                url: getApp().globalData.commonIP + '/bikeRequest/sendRequest',
                method: 'POST',
                header: {
                  'content-type': 'application/json', // 默认值
                  'token': wx.getStorageSync('token')
                },
                data: {
                  nickName: wx.getStorageSync('nickName'),
                  requestType: '单车淤积',
                  bikeName: that.data.bikeName,
                  locName: that.data.name,
                  locRoad: that.data.address,
                  locImg: imgList,
                  sendTime: that.data.sendTime,
                  personalTxt: that.data.inputValue
                },
                success: res => {
                  wx.hideLoading();
                  if (res.data.msg == "token过期，请重新登录" || res.data.msg == "token失效，请重新登录" || res.data.msg == "无效签名，请重新登录" || res.data.msg == "token算法不一致，请重新登录") {
                    wx.showModal({
                      title: '提示',
                      content: res.data.msg,
                      showCancel: false,
                      complete: (res) => {
                        if (res.cancel) {

                        }

                        if (res.confirm) {
                          // 重置全局变量和去除缓存
                          getApp().globalData.wxusername = ''
                          getApp().globalData.wxuseravatar = ''
                          wx.removeStorageSync('nickName')
                          wx.removeStorageSync('avatarUrl')
                          wx.removeStorageSync('token')

                          wx.switchTab({
                            url: '/pages/index/index'
                          })
                        }
                      }
                    })
                    return
                  }
                  wx.showModal({
                    title: '提示',
                    content: res.data.msg,
                    showCancel: false
                  })
                }
              })
            })
            .catch(error => {
              console.error('Error:', error);
            });
        }
      }
    })
  }
})